import { responseData } from '@/share/interface/standard';
import type { NextFunction, Request, Response, Error } from 'express';

const jwt = require('jsonwebtoken');
// 不需要进行 token 验证的路由
const whitelist = [
  '/api/captcha',
  '/api/api-docs',
  '/api/login',
  '/api/wechat',
  '/api/ocr',
  '/api/ocr/vehicle_license',
  '/api/ocr/custom',
  '/api/webhook',
  '/api/text_to_speech',
  '/api/sdk',
];
export function verifyToken(
  req: Request,
  res: Request,
  next: Response
) {
  const isWhitelisted = whitelist.some((item) => {
    const regex = req.url.startsWith(item);
    return regex;
  });
  if (isWhitelisted) return next();

  const authHeader = req.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1];

  if (token == null) {
    return res.status(401).json(
      responseData({
        msg: '未找到 token',
        code: 401,
        data: null,
      })
    );
  }

  jwt.verify(token, 'type-orm-chf', (err, data) => {
    if (err) {
      return res.status(403).json(
        responseData({
          msg: 'token 已过期',
          code: 403,
          data: null,
        })
      );
    }
    if (data.type !== 'admin') {
      req.user_id = data.sub;
    }
    next();
  });
}

// export function verifyError(
//   err: Error,
//   req: Request,
//   res: Response,
//   next: NextFunction
// ) {

//   if (err) {
//     return responseError(err);
//   }

//   next();
// }

/* 
function verifyToken(
  req: Request,
  res: Request,
  next: Response
) {
  const isWhitelisted = whitelist.some((item) => {
    const regex = req.url.startsWith(item);
    return regex;
  });
  if (isWhitelisted) return next();

  const authHeader = req.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1];

  if (token == null) {
    return res.status(401).json(
      responseData({
        msg: '未找到 token',
        code: 401,
        data: null,
      })
    );
  }

  const admin_jwt = jwt.verify(token, 'type-orm-chf');
  const wechat_jwt = jwt.verify(token, 'wechat');
  if (admin_jwt || wechat_jwt) {
    req.user_id = admin_jwt.sub || wechat_jwt.sub; // 将用户信息存储在请求对象中
    return next();
  } else {
    return res.status(401).json(
      responseData({
        msg: 'token 无效',
        code: 403,
        data: null,
      })
    );
  }
}*/
